import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { encryptPassword, makeSalt } from 'src/utils/cryptogram.util';
import { LoginDto } from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  async checkCreateUserForm(createUserDto: CreateUserDto) {
    if (createUserDto.password !== createUserDto.passwordRepeat) {
      throw new HttpException('密码不一致', HttpStatus.BAD_REQUEST);
    }

    const { mobile } = createUserDto;
    const hasUser = await this.userRepository.findOneBy({ mobile });
    if (hasUser) {
      throw new HttpException('手机号已存在', HttpStatus.BAD_REQUEST);
    }
  }

  async create(createUserDto: CreateUserDto) {
    await this.checkCreateUserForm(createUserDto);

    const { nickname, mobile, password } = createUserDto;
    const salt = makeSalt();
    const hashPassword = encryptPassword(password, salt);

    const newUser: User = new User();
    newUser.nickname = nickname;
    newUser.mobile = mobile;
    newUser.password = hashPassword;
    newUser.salt = salt;
    return await this.userRepository.save(newUser);
  }

  async login(loginDto: LoginDto) {
    const { mobile, password } = loginDto;
    const user = await this.userRepository
      .createQueryBuilder('user')
      .addSelect('user.salt')
      .addSelect('user.password')
      .where('user.mobile = :mobile', { mobile })
      .getOne();
    //校验用户是否存在和密码是否正确
    if (!user) {
      throw new HttpException('User not found', HttpStatus.NOT_FOUND);
    }
    const hashPassword = encryptPassword(password, user.salt);
    if (hashPassword !== user.password) {
      throw new HttpException('Password error', HttpStatus.BAD_REQUEST);
    }
    //生成token并返回
    const token = this.jwtService.sign({
      id: user.id,
      mobile: user.mobile,
      nickname: user.nickname,
    });
    return token;
  }
}
